package com.kaibes.module.config;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.core.base.util.StringUtils;
import com.kaibes.core.spring.proxy.Proxy;
import com.kaibes.core.spring.utils.PropertyUtils;
import com.kaibes.core.spring.utils.YamlUtils;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/configs")
public class ConfigApi {
	
	@Proxy
	private MapClient mapClient;
	@Autowired
	private ObjectMapper objectMapper;

	@GetMapping("/{name}")
	@ApiLink(validated = false, value = "读取远程配置")
	public ResponseEntity<JsonNode> get(@PathVariable String name, @RequestParam(required = false) String type) {
		JsonNode config = null;
		if (type == null) {
			try {
				String path = name+".yml";
				config = YamlUtils.getInstance().readAsJsonFromResources(path);
			} catch (IOException e) {
				try {
					String path = name+".properties";
					config = PropertyUtils.getInstance().readAsJsonFromResources(path);
				} catch (IOException e1) {
					try {
						String path = name+".json";
						ClassPathResource source = new ClassPathResource(path);
						config = objectMapper.readTree(source.getInputStream());
					} catch (IOException e2) {
						try {
							String jsonString = mapClient.getByKey(name);
							if (StringUtils.isNotBlank(jsonString)) {
								config = objectMapper.readTree(jsonString);
							}
						} catch (IOException e3) {
						}
					}
				}
			}
		} else {
			try {
				String path = name+"."+type;
				if (type.equals("yml")) {
					config = YamlUtils.getInstance().readAsJsonFromResources(path);
				} else if (type.equals("properties")) {
					config = PropertyUtils.getInstance().readAsJsonFromResources(path);
				} else if (type.equals("json")) {
					ClassPathResource source = new ClassPathResource(path);
					config = objectMapper.readTree(source.getInputStream());
				} else {
					String jsonString = mapClient.getByKey(name);
					if (StringUtils.isNotBlank(jsonString)) {
						config = objectMapper.readTree(jsonString);
					}
				}
			} catch (IOException e) {
			}
		}
		return ResponseFactory.get(config, "读取配置成功", "读取配置失败，配置不存在");
	}
	
}
